<template>
  <!-- <TagsView/> -->
    <!-- 年度考核题库 题库列表-->
    <div class="container">
      <el-row class="" style="margin-bottom: 20px">
        <el-col :span="10" align="left">
          <el-input
            v-model="searchFrom.companyName"
            placeholder="公司名称"
            style="width: 150px; margin-right: 15px"
            clearable
          />
          <el-button class="ordinary" @click="search()">搜索</el-button>
        </el-col>
        <el-col :span="14" align="right">
          <el-button class="ordinary" @click="getExportBtn()"   v-limit="'KHGL:SZHKH:NDKHTK:EXPERT'">批量导出</el-button>
          <el-button type="primary" @click="handleDetect()"     v-limit="'KHGL:SZHKH:GDWNDKH:ALLDISPATH'">批量下发</el-button>
          <el-button type="primary" @click="startAssessment()"  v-limit="'KHGL:SZHKH:GDWNDKH:ALLASSESS'" >批量开启考核</el-button>
          <!--
          <el-button type="primary" @click="unlock()">解锁</el-button>
          <el-button class="lock" @click="handleCopy()">复制</el-button>
          <el-button type="primary" @click="handleAdd()">新建</el-button> -->
        </el-col>
      </el-row>
      <div>
        <el-table
          ref="inOrderTable"
          :data="data.table_list"
          style="width: 100%"
          row-key="id"
          v-loading="data.table_loading"
          @selection-change="selectionChange"
          :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        >
          <el-table-column type="selection" width="55" align="center" :reserve-selection="false" fixed="left"/>
          <!-- <el-table-column prop="number" label="序号" align="left"  width="50"  fixed="left">
            <template #default="{scope,$index}">
              {{ $index + 1}}
            </template>
          </el-table-column> -->
          <el-table-column type="index" :index="indexMethod" align="center" label="序号" width="50" fixed="left" />
          <el-table-column prop="questionBank.name" label="考核名称" align="center" width="180"  fixed="left" />
          <el-table-column prop="companyName" label="公司" align="center" width="200" />
          <el-table-column prop="questionBank.age" label="年度" align="center" width="100" />
          <el-table-column prop="questionNumber" label="题目数量" align="center" width="100" />
          <el-table-column label="总分" align="center" width="100" >
            <template #default="scope">
              <span span   v-if="scope.row.standardPlusPoints != 0">{{ scope.row.standardAddPoints}} +  {{scope.row.standardPlusPoints}}</span>
              <span span  v-if="scope.row.standardPlusPoints == 0">{{ scope.row.standardAddPoints + scope.row.standardPlusPoints}}</span>
            </template>
          </el-table-column>
          <el-table-column label="自评总分" align="center" width="100" >
            <template #default="scope">
              <span span  v-if="scope.row.selfPlusPoints != 0">{{ scope.row.selfAddPoints}} +  {{scope.row.selfPlusPoints}}</span>
              <span span  v-if="scope.row.selfPlusPoints == 0">{{ scope.row.selfAddPoints + scope.row.selfPlusPoints}}</span>
            </template>
          </el-table-column>
          <el-table-column label="复评总分" align="center" width="100" >
            <template #default="scope">
              <span span  v-if="scope.row.repeatPlusPoints != 0">{{ scope.row.repeatAddPoints}} +  {{scope.row.repeatPlusPoints}}</span>
              <span span  v-if="scope.row.repeatPlusPoints == 0">{{ scope.row.repeatAddPoints + scope.row.repeatPlusPoints}}</span>
            </template>
          </el-table-column>
          <el-table-column prop="reportNumber" label="报告数量" align="center" width="100" />
          <el-table-column prop="internalAuditFeedback" label="内审反馈" align="center" width="100" />
          <el-table-column prop="createUsername" label="创建人" align="center" width="100"  />
          <el-table-column prop="createTime" label="创建时间" align="center" width="150"/>
          <el-table-column prop="answerPeopleName" label="自评人" align="center" width="100"  />
          <el-table-column prop="answerTime" label="自评时间" align="center" width="150"/>
          <el-table-column prop="internalAuditPeopleName" label="内部审核人" align="center" width="100"  />
          <el-table-column prop="internalAuditTime" label="内部审核时间" align="center" width="150"/>
          <el-table-column prop="totalAuditPeopleName" label="总部审核人" align="center"  width="100" />
          <el-table-column prop="totalAuditTime" label="总部审核时间" align="center" width="150"/>
          <el-table-column prop="auditStatus_text" label="状态" align="center" width="110"  />
          <el-table-column prop="address" label="操作" align="center" width="480" fixed="right">
            <template #default="scope">
              <!-- <el-button type="primary" @click="handleEdit(scope.row,'look')" v-if="scope.row.lockFlag == '1'">查看</el-button> -->
              <el-button  v-if="scope.row.auditStatus == 1"  @click="giveScoreManage(scope.row)" type="primary" v-limit="'KHGL:SZHKH:GDWNDKH:MANAGE'" >管理</el-button>
              <el-button  v-if="scope.row.auditStatus == 1"  @click="closeItem(scope.row)" v-limit="'KHGL:SZHKH:GDWNDKH:DELETE'" >删除</el-button>
              <el-button  v-if="scope.row.auditStatus == 1"  @click="handleDetectOne(scope.row)" type="primary" v-limit="'KHGL:SZHKH:GDWNDKH:DISPATH'" >下发</el-button>
              <el-button  v-if="scope.row.auditStatus == 2 || scope.row.auditStatus == 3 || scope.row.auditStatus == 4|| scope.row.auditStatus == 9"
              type="primary"  @click="goLook(scope.row,'look')" v-limit="'KHGL:SZHKH:GDWNDKH:VIEW'" >查看</el-button>
              <el-button  v-if="scope.row.auditStatus == 2"  @click="withdraw(scope.row)" v-limit="'KHGL:SZHKH:GDWNDKH:REVOKE'">撤回</el-button>
              <el-button  v-if="scope.row.auditStatus == 2" @click="startAssessmentOne(scope.row)" type="primary" v-limit="'KHGL:SZHKH:GDWNDKH:ASSESS'">开启考核</el-button>
<!--              <el-button  v-if="scope.row.auditStatus == 7" type="primary"   @click="reportUpload(scope.row,'update')"  v-limit="'KHGL:SZHKH:GDWNDKH:CKECKANDEXAMINE'">查看并审核</el-button>-->
              <el-button v-if="scope.row.auditStatus == 7" type="primary" @click="goLook(scope.row,'repeat')" v-limit="'KHGL:SZHKH:GDWNDKH:REPEAT'">复评</el-button>
              <el-button v-if="scope.row.auditStatus == 7 || scope.row.auditStatus == 9" type="primary" @click="goPreview(scope.row)" v-limit="'KHGL:SZHKH:GDWNDKH:SELFPREVIEW'">自评预览</el-button>
              <el-button v-if="scope.row.auditStatus == 7 || scope.row.auditStatus == 9" @click="reportUpload(scope.row,'look')" type="primary" v-limit="'KHGL:SZHKH:GDWNDKH:VIEWREPORT'">查看报告</el-button>
              <el-button v-if="scope.row.auditStatus == 7 || scope.row.auditStatus == 9" type="primary" @click="downAll(scope.row)" v-limit="'KHGL:SZHKH:GDWNDKH:DOWNLOAD'">下载全部附件</el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="example-pagination-block">
              <el-pagination
                :current-page="searchFrom.current"
                :page-size="searchFrom.size"
                :page-sizes="[10, 20, 30, 40,50,100]"
                background
                layout="prev, pager, next ,total,sizes,jumper"
                :total="data.page.total"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
            />
        </div>
      </div>

      <!-- <scoreManModal
        v-model:visible="data.scoreManVisible"
        :handleRow="data.handleRowData"
        :apiPackage="apiPackage"
      ></scoreManModal> -->
    </div>
  </template>
  <script lang="ts" setup>
  import { reactive, ref } from "vue";
  // import Table from '../../../components/indexTable.vue'
  import { dataDictionary } from "@/api/dict";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRoute, useRouter } from "vue-router";
import * as api from "../../api/eachUnit";
  import {exportStandardIndexRequest, withoutRequest} from "../../api/eachUnit";
  import {tips} from "@/views/science/components/tips/tips";

  const searchFrom = reactive({
    //查询
    companyName: "",
    size:10,
    current:1,
  });
  // const refreshPage:any=inject('refreshPage', Function, true);
  let standardType = ref("1"); //该参数决定显示的是中交还是中咨的标准库纸指标
  const route = useRoute();
  const router = useRouter();
  const inOrderTable = ref()

  standardType.value = route.meta.type as string;
  const apiPackage = reactive({
    detail: "scoreManDetailRequest",
    score: "updateScoreRuleRequest",
    insert: "insertItemSetRequest",
    update: "updateItemSetRequest",
    delete: "deleteItemSetRequest",
  });

  const pagination = reactive({  //分页器信息
      pageSize:10,
      currentPage:1,
  })
  //弹出框form
  const form = reactive({
    name:'',
    age:'',
    remark:'',
    id:'',
  })
  const rules = reactive({
      name: [
        { required: true, message: '请输入考核名称', trigger: 'blur' },
      ],
      age: [
        { required: true, message: '请选择年度', trigger: 'blur', },
      ]
      })

  let data = reactive<any>({
    table_list: [],
    modalVisible: false,
    opType: "add", //add,edit,copy
    handleRowData: null, //正在处理的行数据
    scoreManVisible: false,
    table_loading: false,
    page: { page: 1, limit: 10, total: 0 },
    reportTable:[],//查看报告弹窗数据
  });
  const dictDatas = reactive({
    dict_indexTypes: [],
    dict_indexNames: [],
    dict_scoreTypes: [],
    dict_scoreMethods: [],
    dict_scoreSources_zj: [],
    dict_scoreSources_zz: [],
    dict_scoreCompose_zj: [],
    dict_scoreCompose_zz: [],
  }); //字典值
  let selectedRows = ref<any>([]);

  //---------------------------------------------页面按钮事件
  //搜索
  const search = () => {
    gettargetlist();
  };
  //批量导出
  const getExportBtn = () => {
    ElMessageBox.confirm("确定要导出吗?", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }).then(() => {
    exportStandardIndexRequest({
        companyName:searchFrom.companyName
      })

    });
  };
  //批量下发
  const handleDetect = () => {
    if (selectedRows.value.length === 0) {
      ElMessage({
        message: "请选择数据后下发！",
        type: "warning",
      });
    }else {
      ElMessageBox.confirm("确定要批量下发吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        let ids = [] as any
        selectedRows.value.forEach(e  => {
          ids.push(e.id)
        });
        api
          .distributeIndexRequest({
            ids: ids
          })
          .then((res) => {
            if (res.data.code == 200) ElMessage.success("下发成功");
            gettargetlist();
          });
      });
    }
  };
  //批量下发 单个
  const handleDetectOne = (val) => {
    api
      .distributeIndexRequest({
        ids: [val.id]
      })
      .then((res) => {
        if (res.data.code == 200) ElMessage.success("下发成功");
        gettargetlist();
      });
  };
  //批量开启考核
  const startAssessment = () =>{
    if (selectedRows.value.length === 0) {
      ElMessage({
        message: "请选择考核数据",
        type: "warning",
      });
    }else {
      ElMessageBox.confirm("确定要批量开启考核吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        let ids = [] as any
        selectedRows.value.forEach(e  => {
          ids.push(e.id)
        });
        api
          .startAssessmentRequest({
            ids: ids
          })
          .then((res) => {
            if (res.data.code == 200) ElMessage.success("批量考核成功");
            gettargetlist();

          });
      });
    }
  }
  //批量开启考核   单个
  const startAssessmentOne = (val) =>{
        api
          .startAssessmentRequest({
            ids: [val.id]
          })
          .then((res) => {
            if (res.data.code == 200) ElMessage.success("考核成功");
            gettargetlist();

      });
  }
  //删除
  const closeItem = (val) =>{
    ElMessageBox.confirm("确定要删除选中数据吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        api
          .deleteRequest({
            ids: [val.id]
          })
          .then((res) => {
            if (res.data.code == 200) ElMessage.success("删除成功");
            gettargetlist();
          });
      });
  }
  //撤回
  const withdraw = (val) =>{
    ElMessageBox.confirm("确定要撤回选中数据吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
/*        api.withdrawRequest({id:val.id}).then(res =>{
            if (res.data.code == 200) ElMessage.success("撤回成功");
            gettargetlist();  可能调错接口了改的
          }) */
        api.withoutRequest({ids:[val.id]}).then(res =>{
            if (res.data.code == 200) ElMessage.success("撤回成功");
            gettargetlist();
          })
      });
  }
  //管理 --前往考核管理页面
  const giveScoreManage = (item) => {
    router.push({
      path: "/examineManage/digitalExamine/manage",
      query: {
        // bankId:item.id,之前的
        /*bankId:item.bankId, 第二次改*/
        id:item.id,
        bankId:item.bankId,
        status: item.auditStatus_text
      },
    });
  };

  //查看
  const goLook = (item,type) => {
    router.push({
      path: "/examineManage/digitalExamine/examineDetail",
      query: {
        bankId:item.id,
        type:type,
      },
    });
  };
  //下载全部附件
  const downAll = (val) =>{
    api.downAllRequest({id:val.id}).then(res =>{
      console.log('res',res.data.data);
      if(res.data.data.length==0){
        tips('暂无附件', 'warning');
        return;
      }
      if(res.data.data.length > 0){
        res.data.data.forEach(e =>{
          console.log('e',e);
            // 有一些下载url是http开头的，在https的域名下面下载的话会有mix content问题，这里转成https
              if (e.path.startsWith('http:')) {
                const replaceUrl = e.path.replace('https:', 'http:');
                downloadResource(replaceUrl,e.fileName);
              } else {
                downloadResource(val.path,e.fileName);
              }
        })
      }
    })
  }
  const downloadResource = (url,name) => {
    const a = document.createElement('a');
          a.style.display = 'none';
          a.href = url
          a.download = name
          document.body.appendChild(a);
          a.click();
          document.body.removeChild(a);
  }
  //查看报告
  const reportUpload = (item,type) =>{
    router.push({
      path: "/examineManage/digitalExamine/reportUpload",
      query: {
        bankId:item.id,
        name:item.companyName,
        year:item.questionBank.age,
        type:type
      },
    });
  }
  //前往  自评预览
  const goPreview = (val) =>{
    router.push({
      path: "/examineManage/digitalExamine/selfPreview",
      query: {
        bankId:val.id,
      },
    });
  }
  //----------------------------------------------其他逻辑事件
  const indexMethod = (index)=>{
    return searchFrom.size*(searchFrom.current-1) +index+1
  }
  //选中
  const selectionChange = (arr) => {
    selectedRows.value = arr;
  };
  //解锁
  const unlock = () =>{
    if (selectedRows.value.length === 0) {
      ElMessage({
        message: "请选择数据后解锁！",
        type: "warning",
      });
    }else {
      ElMessageBox.confirm("确定要解锁选中数据吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        // let sel_ids=selectedRows.value.map(item=>{return item.id});
        let ids = [] as any
        console.log('解锁value',selectedRows.value);

        selectedRows.value.forEach(e  => {
          ids.push(e.id)
        });

        console.log('解锁1 ids',ids);

        api
          .hadUnLock({
            ids: ids
          })
          .then((res) => {
            if (res.data.code == 200) ElMessage.success("解锁成功");
            gettargetlist();
          });

          // ids.length = []
      });
    }
  }
  const ruleFormRef = ref()
  //关闭弹窗
  const close = () =>{
    data.modalVisible = false
    ruleFormRef.value.resetFields()
    form.name = ''
    form.age = ''
    form.remark = ''
    form.id = ''
  }
  const getLockBtn = () => {
    //复制
  };
  const handleAdd = () => {
    //新增
    data.opType = "add";
    data.modalVisible = true;
  };
  //编辑
  const handleEdit = (item,type) => {
    data.opType = type;
    form.age = item.age
    form.name = item.name
    form.remark = item.remark
    form.id = item.id
    console.log('item',item,'form=>',form);
    // data.handleRowData = item;

    data.modalVisible = true;
  };
  //点击复制按钮------复制
  const handleCopy = () => {
    if (selectedRows.value.length !== 1) {
      ElMessage({
        message: "请选择一条数据复制",
        type: "warning",
      });
    } else if(selectedRows.value.length > 1){
      ElMessage({
        message: "只允许选择一条数据复制",
        type: "warning",
      });
    }else{
      data.opType = "copy";
      // data.handleRowData = selectedRows.value[0];
      data.modalVisible = true;
      form.age = selectedRows.value[0].age
      form.name = selectedRows.value[0].name
      form.remark = selectedRows.value[0].remark
    }
  };
  const getDictDatas = () => {
    return new Promise((resolve, reject) => {
      data.table_loading = true;
      let dictIds = [
        "KHGL_CLASS_INDEX_NAME_CODE",
        "KHGL_INDEX_TYPE_CODE",
        "KHGL_SCORE_METHOD_CODE",
        "KHGL_SCORE_TYPE_CODE",
        "KHGL_ZJ_EXAMINE_SCORE_METHOD_CODE",
        "KHGL_ZZ_EXAMINE_SCORE_METHOD_CODE",
      ];
      dataDictionary(dictIds).then((res) => {
        let response = res.data.data;
        dictDatas.dict_indexTypes = response.KHGL_INDEX_TYPE_CODE;
        dictDatas.dict_indexNames = response.KHGL_CLASS_INDEX_NAME_CODE;
        dictDatas.dict_scoreTypes = response.KHGL_SCORE_TYPE_CODE;
        dictDatas.dict_scoreMethods = response.KHGL_SCORE_METHOD_CODE;
        dictDatas.dict_scoreSources_zj = response.KHGL_ZJ_EXAMINE_SCORE_METHOD_CODE;
        dictDatas.dict_scoreSources_zz = response.KHGL_ZZ_EXAMINE_SCORE_METHOD_CODE;
        if (standardType.value === "1") {
          //中交
          response.KHGL_ZJ_EXAMINE_SCORE_METHOD_CODE.map((item) => {
            dictDatas.dict_scoreCompose_zj = dictDatas.dict_scoreCompose_zj.concat(
              item.children
            );
          });
        } else {
          response.KHGL_ZZ_EXAMINE_SCORE_METHOD_CODE.map((item) => {
            dictDatas.dict_scoreCompose_zz = dictDatas.dict_scoreCompose_zz.concat(
              item.children
            );
          });
        }

        resolve(1);
      });
    });
  };
  // let table_list=reactive<any>([]);
  const gettargetlist = () => {
    //获取标准指标库列表
    data.table_loading = true;
    api
      .getEveryList({
        ...searchFrom,
      })
      .then((res) => {
        console.log('res',res);
        data.table_loading = false;
        data.table_list = res.data.data.records;
        data.page.total = res.data.data.total;
      });
      selectedRows.value = []
      inOrderTable.value.clearSelection()
  };
   //分页操作
  const handleSizeChange = (val) =>{
    pagination.pageSize = val
    searchFrom.size = val
    gettargetlist()
  }

  const handleCurrentChange = (val) =>{
    pagination.currentPage = val
    searchFrom.current = val
    gettargetlist()
  }
  getDictDatas().then(() => {
    gettargetlist();
  });
  </script>
  <style lang="scss" scoped>
  .container {
    background-color: white;
    padding: 20px;
    overflow-y: auto;
  }

  // :deep(.el-dialog__body) {
  //   padding: 0 !important
  // }
  :deep(.el-dialog__body) {
    padding: 0;
  }

  .dialogCloseBtn {
    position: absolute;
    top: 20px;
    right: 20px;
  }

  // .el-col {
  //   line-height: 60px;
  // }

  .pageName {
    font-weight: 700;
  }

  .el-form-item {
    .el-input {
      width: 100px;
    }

    .el-select {
      width: 100px;
    }
  }

  :deep(.demo-tabs > .el-tabs__content) {
    max-height: 500px;
    overflow-y: scroll;
    scrollbar-width: none;
    /* Firefox */
    -ms-overflow-style: none;
    /* IE 10+ */
  }

  :deep(.demo-tabs > .el-tabs__content::-webkit-scrollbar) {
    display: none;
    /* Chrome Safari */
  }
  .demo-form-inline .el-form-item {
  width: 30%;
}

:deep(.labelHeight .el-form-item__label) {
  line-height: 20px;
}
  </style>
